import 'package:gold/app/user_provider.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_address.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/model/goods_detail_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';

/// @description:
/// @author tangzhentao
/// @created at 20:02 2024/11/30


class IntegralOrderViewmodel extends Viewmodel {
  /// 积分商品信息
  final GoodsDetailModel goods;

  /// 数量
  int _number = 1;
  int get number => _number;
  set number(int value) {
    if (_number != value) {
      _number = value;
      _calMoneyByNumberChanged();
      notifyListeners();
    }
  }

  /// 地址
  AddressModel? _address;
  AddressModel? get address => _address;
  set address(AddressModel? value) {
    if (_address != value) {
      _address = value;
      notifyListeners();
    }
  }

  bool? _balanceEnable = false;
  /// 是否余额抵扣
  bool? get balanceEnable => _balanceEnable;
  set balanceEnable(bool? value) {
    if (_balanceEnable != value) {
      _balanceEnable = value;
      _calMoneyByBalanceEnableChanged();
      notifyListeners();
    }
  }
  double _balanceNumber = 0;
  /// 余额抵扣数量
  double get balanceNumber =>_balanceNumber;

  double _payAmount = 0;
  /// 支付金额
  double get payAmount => _payAmount;

  double _deduction = 0;
  /// 折扣总金额
  double get deduction => _deduction;

  IntegralOrderViewmodel(this.goods, int count) {
    _number = count;
    _updateAmount();
  }

  /// 更新用户剩余金额
  Future _updateAmount() async {
    final userProvider = XfgNav.read<UserProvider>();
    await userProvider.updateProfile();
    _calMoney();
    /// 获取默认地址
    final result = await Http().request<AddressModel>(ApiAddress.addressDefault, showErrorMsg: false);
    if (result.success && result.data!= null) _address = result.data;
    notifyListeners();
  }

  /// 初始化计算金额
  void _calMoney() {
    final user = XfgNav.read<UserProvider>().user;
    final amount = user.amount?? 0.0;
    double total = (goods.price?? 0) * number + (goods.freight?? 0);
    _balanceEnable = (user.amount?? 0) <= 0 || total <= 0 ? null:false;
    _deduction = 0;
    _balanceNumber = 0;
    /// 处理余额抵扣
    if (_balanceEnable != null) _balanceNumber = total < amount ? total:amount;
    _payAmount = total;
  }

  /// 数量变化计算金额
  void _calMoneyByNumberChanged() {
    final user = XfgNav.read<UserProvider>().user;
    final amount = user.amount?? 0.0;
    double total = (goods.price?? 0) * number + (goods.freight?? 0);
    _balanceEnable = (user.amount?? 0) <= 0 || total <= 0 ? null:false;
    _deduction = 0;
    _balanceNumber = 0;
    /// 处理余额抵扣
    if (_balanceEnable != null) _balanceNumber = total < amount ? total:amount;
    _payAmount = total;
  }

  /// 选中变化计算金额
  void _calMoneyByBalanceEnableChanged() {
    final user = XfgNav.read<UserProvider>().user;
    final amount = user.amount?? 0.0;
    double total = (goods.price?? 0) * number + (goods.freight?? 0);
    _deduction = 0;
    _balanceNumber = 0;
    /// 处理余额抵扣
    _balanceNumber = total < amount ? total:amount;
    if (_balanceEnable == true) {
      total = total - _balanceNumber;
      _deduction += _balanceNumber;
    }
    _payAmount = total < 0 ? 0:total;
  }

  /// 选择地址
  Future pickAddress() async {
    final result = await XfgNav.pushNamed<AddressModel>(Routes.myAddress, arguments: true);
    if (result != null) {
      address = result;
    }
  }

  /// 立即支付
  Future payNow() async {
    if (_address == null) {
      '请先选择收货地址'.info();
      return;
    }
    final orderRequest = OrderRequest(_payAmount, _address?.id, goods.id, _number, 0, _deduction, null);
    final result = await Http().request<int>(ApiOrder.create, data: orderRequest.toJson(), loadingText: '创建订单...');
    if (result.success) {
      XfgNav.read<UserProvider>().updateProfile();
      if (result.data != null) {
        if (_payAmount > 0) {
          XfgNav.pushReplacementNamed(Routes.pay, arguments: {'type': ProductType.points, 'id': result.data!, 'amount': _payAmount});
        } else {
          XfgNav.pushReplacementNamed(Routes.paySuccess, arguments: {'type': ProductType.points, 'id': result.data!});
        }
      } else {
        '订单信息异常'.error();
      }
    }
  }
}